import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  InputNumber,
  Switch,
  Space,
  Checkbox,
  Row,
  Col,
  message,
  Divider,
  Typography,
  Tag,
  Modal,
  ColorPicker
} from 'antd';
import CustomMDEditor from '../../components/MarkdownEditor/CustomMDEditor';
import { SaveOutlined, PlusOutlined } from '@ant-design/icons';
import { useParams } from 'react-router-dom';
import { problemManagementApi, buildProblemCreateRequest } from '../../api/services/Problem/problemManagement';
import { tagManagementApi } from '../../api/services/Problem/tagManagement';
import type {  Tag as TagType, ProblemCase } from '../../api/dto/problemManagement';
import type { TagCreateRequest } from '../../api/services/Problem/tagManagement';


import './ProblemManagemen.less';

const { Title, Text } = Typography;
const { Option } = Select;
const { TextArea } = Input;

const ProblemManagement: React.FC = () => {
const { id: problemId } = useParams<{ id: string }>();
const [form] = Form.useForm();
const [tagForm] = Form.useForm();
const [loading, setLoading] = useState(false);

// 标签相关状态
const [availableTags, setAvailableTags] = useState<TagType[]>([]);
const [isTagModalVisible, setIsTagModalVisible] = useState(false);
const [tagLoading, setTagLoading] = useState(false);
  
  // Markdown编辑器状态
const [description, setDescription] = useState(`**题目描述**

请在此处输入题目描述...

**输入描述**

请在此处描述输入格式和要求...

**输出描述**

请在此处描述输出格式和要求...

**示例 1**

**输入：**
\`\`\`
请在此处输入样例输入...
\`\`\`

**输出：**
\`\`\`
请在此处输入样例输出...
\`\`\`

**提示**

请在此处输入解题提示（可选）...

**备注**

请在此处输入补充说明（可选）...`);
  
  // 测试用例状态
  const [testCases, setTestCases] = useState<ProblemCase[]>([{
    input: '',
    output: '',
    score: 0,
    status: 0
  }]);

  // 支持的编程语言选项
  const languageOptions = [
    { label: 'C', value: 'c' },
    { label: 'C++', value: 'cpp' },
    { label: 'Java', value: 'java' },
    { label: 'Python 3', value: 'python3' },
    { label: 'JavaScript', value: 'javascript' },
    { label: 'Go', value: 'go' },
    { label: 'Rust', value: 'rust' }
  ];

  // 难度选项
  const difficultyOptions = [
    { label: '简单', value: 'easy', color: '#52c41a' },
    { label: '中等', value: 'medium', color: '#faad14' },
    { label: '困难', value: 'hard', color: '#f5222d' }
  ];

  // 题目类型选项
  const typeOptions = [
    { label: 'ACM模式', value: 0 },
    { label: 'OI模式', value: 1 }
  ];

  // 权限选项
  const authOptions = [
    { label: '公开', value: 1 },
    { label: '私有', value: 2 },
    { label: '比赛题目', value: 3 },
    { label: '训练题目', value: 4 }
  ];

  // 加载标签列表
  const loadTags = async () => {
    try {
      const response = await tagManagementApi.getTagList();
      console.log('标签列表响应:', response);
      if (response.code === 200 || response.code === 1) {
        setAvailableTags(response.data || []);
      } else {
        console.error('加载标签列表失败:', response.message);
      }
    } catch (error) {
      console.error('加载标签列表失败:', error);
    }
  };

  // 初始化表单数据
  useEffect(() => {
      form.setFieldsValue({
        problemId: '',
        type: 0,
        auth: 1,
        difficulty: 'medium',
        timeLimit: 1000,
        memoryLimit: 256,
        stackLimit: 128,
        supportedLanguages: ['c', 'cpp', 'java', 'python3'],
        isPublic: false,
        isRemote: false,
        isShowJudgeDetails: true,
        tags: [],
        author: 'admin',
        source: '',
        inputDescription: '',
        outputDescription: ''
      });
      
      // 加载标签列表
      loadTags();
    
  }, [problemId, form]);



  // 添加测试用例
  const addTestCase = () => {
    setTestCases([...testCases, { input: '', output: '', score: 0, status: 0 }]);
  };

  // 删除测试用例
  const removeTestCase = (index: number) => {
    if (testCases.length > 1) {
      const newTestCases = testCases.filter((_, i) => i !== index);
      setTestCases(newTestCases);
    }
  };

  // 更新测试用例
  const updateTestCase = (index: number, field: keyof ProblemCase, value: any) => {
    const newTestCases = [...testCases];
    newTestCases[index] = { ...newTestCases[index], [field]: value };
    setTestCases(newTestCases);
  };

  // 创建标签
  const handleCreateTag = async (values: any) => {
    try {
      setTagLoading(true);
      
      // 处理颜色值
      const color = typeof values.color === 'string' ? values.color : values.color?.toHexString?.() || '#1890ff';
      
      const tagData: TagCreateRequest = {
        name: values.name,
        color,
        oj: values.oj,
        gid: null,
        tcid: null
      };
      
      const response = await tagManagementApi.createTag(tagData);
      console.log('创建标签响应:', response);
      if (response.code === 200) {
        message.success('标签创建成功');
        setIsTagModalVisible(false);
        tagForm.resetFields();
        // 重新加载标签列表
        await loadTags();
        // 自动选中新创建的标签
        const currentTags = form.getFieldValue('tags') || [];
        const newTagName = response.data?.name || values.name;
        form.setFieldsValue({
          tags: [...currentTags, newTagName]
        });
      } else {
        message.error(response.message || '标签创建失败');
      }
    } catch (error) {
      console.error('创建标签失败:', error);
      message.error('标签创建失败');
    } finally {
      setTagLoading(false);
    }
  };





  // 提交表单
  const handleSubmit = async (values: any) => {
    try {
      // 手动验证所有必填字段，使用 message.error 提示
      if (!values.title?.trim()) {
        message.error('请输入题目名称');
        return;
      }
      if (!values.difficulty) {
        message.error('请选择题目难度');
        return;
      }
      if (!values.timeLimit) {
        message.error('请设置时间限制');
        return;
      }
      if (!values.memoryLimit) {
        message.error('请设置内存限制');
        return;
      }
      if (!values.supportedLanguages || values.supportedLanguages.length === 0) {
        message.error('请选择至少一种编程语言');
        return;
      }
      if (!description?.trim()) {
        message.error('请输入题目描述');
        return;
      }
      
      setLoading(true);
      
      const requestData = buildProblemCreateRequest(values, description, testCases, availableTags);

      let response;

      response = await problemManagementApi.createProblem(requestData);
      
      console.log('创建题目响应:', response);
      if (response.code === 200 || response.code === 1) {
        message.success(problemId ? '题目更新成功！' : '题目创建成功！');
        if (!problemId) {
          // 新建成功后重置表单
          form.resetFields();
          setDescription(`## 题目描述\n\n请在此处输入题目描述...\n\n## 输入描述\n\n请在此处描述输入格式和要求...\n\n## 输出描述\n\n请在此处描述输出格式和要求...\n\n## 样例\n\n### 样例 1\n\n**输入：**\n\`\`\`\n请在此处输入样例输入...\n\`\`\`\n\n**输出：**\n\`\`\`\n请在此处输入样例输出...\n\`\`\`\n\n## 提示\n\n请在此处输入解题提示（可选）...\n\n## 备注\n\n请在此处输入补充说明（可选）...`);
          setTestCases([{ input: '', output: '', score: 0, status: 0 }]);
        }
      } else {
        message.error(response.message || '操作失败');
      }
    } catch (error) {
      console.error('Submit error:', error);
      message.error('操作失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 保存草稿
  const handleSaveDraft = () => {
    const values = form.getFieldsValue();
    const draftData = {
      ...values,
      description,
      testCases
    };
    message.success('草稿已保存');
  };

  return (
    <div className="problem-management">
      <div className="problem-management-container">
        {/* 左侧侧边栏 */}
        <div className="problem-sidebar">
          <div className="sidebar-header">
            <Title level={4} style={{ margin: 0, color: 'white' }}>题目管理</Title>
          </div>
          <div className="sidebar-menu">
            <div className="menu-item active">
              <span>创建题目</span>
            </div>
            <div className="menu-item">
              <span>题目列表</span>
            </div>
            <div className="menu-item">
              <span>题目分类</span>
            </div>
            <div className="menu-item">
              <span>导入/导出</span>
            </div>
          </div>
          <div className="sidebar-stats">
            <Title level={5} style={{ margin: '16px 0 8px 0', color: '#2c3e50' }}>题目统计</Title>
            <div className="stat-item">
              <div className="stat-bar">
                <div className="stat-progress" style={{ width: '60%', backgroundColor: '#52c41a' }}></div>
              </div>
              <div className="stat-info">
                <span>全部题目</span>
                <span>248</span>
              </div>
            </div>
            <div className="stat-item">
              <div className="stat-bar">
                <div className="stat-progress" style={{ width: '40%', backgroundColor: '#faad14' }}></div>
              </div>
              <div className="stat-info">
                <span>待审核</span>
                <span>15</span>
              </div>
            </div>
            <div className="stat-item">
              <div className="stat-bar">
                <div className="stat-progress" style={{ width: '80%', backgroundColor: '#52c41a' }}></div>
              </div>
              <div className="stat-info">
                <span>已发布</span>
                <span>189</span>
              </div>
            </div>
          </div>
        </div>
        
        {/* 右侧内容区域 */}
        <div className="problem-content">
        <div className="problem-content-inner">
          {/* 页面标题区域 */}
          <div className="page-header-section">
            <div className="page-title-area">
              <h2 className="page-title">创建新题目</h2>
              <div className="page-actions">
                <Button 
                  icon={<SaveOutlined />}
                  style={{
                    backgroundColor: '#ffffff',
                    color: '#666666',
                    border: '1px solid #d9d9d9',
                    marginRight: '8px'
                  }}
                >
                  保存草稿
                </Button>
                <Button 
                  type="primary"
                  style={{
                    backgroundColor: '#1890ff',
                    borderColor: '#1890ff'
                  }}
                >
                  发布题目
                </Button>
              </div>
            </div>
          </div>
            <Form
              form={form}
              layout="vertical"
              onFinish={handleSubmit}
              className="problem-form"
            >
        {/* 基本信息 */}
        <Card title="基本信息" className="form-section">
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="title"
                label="题目名称"
              >
                <Input placeholder="请输入题目名称" maxLength={100} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="problemId"
                label="题目ID"
              >
                <Input placeholder="请输入题目ID（如：SWUST-OJ-1000）" maxLength={50} />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={24}>
            <Col span={8}>
              <Form.Item
                name="difficulty"
                label="难度"
              >
                <Select placeholder="请选择难度">
                  {difficultyOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      <Tag color={option.color}>{option.label}</Tag>
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="type"
                label="题目类型"
              >
                <Select placeholder="请选择题目类型">
                  {typeOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="auth"
                label="权限设置"
              >
                <Select placeholder="请选择权限">
                  {authOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          
          <Form.Item
            name="tags"
            label="题目标签"
            help="选择已有标签或创建新标签"
          >
            <Select
              mode="multiple"
              placeholder="请选择标签"
              dropdownRender={(menu) => (
                <>
                  {menu}
                  <Divider style={{ margin: '8px 0' }} />
                  <Space style={{ padding: '0 8px 4px' }}>
                    <Button
                      type="text"
                      icon={<PlusOutlined />}
                      onClick={() => setIsTagModalVisible(true)}
                    >
                      创建新标签
                    </Button>
                  </Space>
                </>
              )}
            >
              {availableTags.map((tag, index) => (
                <Option key={tag.id || `${tag.name}-${index}`} value={tag.name}>
                  <Tag color={tag.color}>{tag.name}</Tag>
                </Option>
              ))}
            </Select>
          </Form.Item>
        </Card>

        {/* 题目描述 */}
        <Card title="题目内容" className="form-section">
          <div className="markdown-editor-container">
            <Text type="secondary" className="editor-help">
              支持Markdown语法，可以插入数学公式、代码块等。模板已包含题目描述、输入输出描述、示例、提示和备注部分。
            </Text>
            <CustomMDEditor
              value={description}
              onChange={(val) => setDescription(val || '')}
              preview="live"
              height={600}
              data-color-mode="light"
              placeholder="请使用模板编写完整的题目内容"
            />
          </div>
        </Card>



        {/* 题目设置 */}
        <Card title="题目设置" className="form-section">
          <Row gutter={24}>
            <Col span={8}>
              <Form.Item
                name="timeLimit"
                label="时间限制 (ms)"
              >
                <InputNumber
                  min={100}
                  max={10000}
                  step={100}
                  placeholder="1000"
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="memoryLimit"
                label="内存限制 (MB)"
                rules={[{ required: true, message: '请输入内存限制' }]}
              >
                <InputNumber
                  min={32}
                  max={1024}
                  step={32}
                  placeholder="256"
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="stackLimit"
                label="栈限制 (MB)"
                rules={[{ required: true, message: '请输入栈限制' }]}
              >
                <InputNumber
                  min={32}
                  max={512}
                  step={32}
                  placeholder="128"
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="source"
                label="题目来源"
              >
                <Input placeholder="请输入题目来源，如：ACM-ICPC、Codeforces等" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="author"
                label="题目作者"
                rules={[{ required: true, message: '请输入题目作者' }]}
              >
                <Input placeholder="请输入题目作者" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={24}>
            <Col span={8}>
              <Form.Item
                name="isPublic"
                label="是否公开"
                valuePropName="checked"
              >
                <Switch checkedChildren="公开" unCheckedChildren="私有" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="isRemote"
                label="远程判题"
                valuePropName="checked"
              >
                <Switch checkedChildren="是" unCheckedChildren="否" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="isShowJudgeDetails"
                label="显示评测详情"
                valuePropName="checked"
                initialValue={true}
              >
                <Switch checkedChildren="显示" unCheckedChildren="隐藏" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="supportedLanguages"
            label="支持的编程语言"
            rules={[{ required: true, message: '请选择至少一种编程语言' }]}
          >
            <Checkbox.Group options={languageOptions} />
          </Form.Item>
        </Card>

        {/* 测试用例 */}
        <Card 
          title="测试用例" 
          className="form-section"
          extra={
            <Button 
              onClick={addTestCase}
              style={{ 
                backgroundColor: '#ffffff',
                color: '#666666',
                border: '1px solid #d9d9d9'
              }}
            >
              + 添加测试用例
            </Button>
          }
        >
          {testCases.map((testCase, index) => (
            <div key={index} className="test-case-item">
              <div className="test-case-header">
                <Text strong>测试用例 {index + 1}</Text>
                <Space>
                  <Switch
                    size="small"
                    checked={testCase.status === 0}
                    onChange={(checked) => updateTestCase(index, 'status', checked ? 0 : 1)}
                    checkedChildren="公开"
                    unCheckedChildren="隐藏"
                  />
                  {testCases.length > 1 && (
                    <Button 
                      type="text" 
                      danger 
                      size="small"
                      onClick={() => removeTestCase(index)}
                    >
                      删除
                    </Button>
                  )}
                </Space>
              </div>
              <Row gutter={16}>
                <Col span={12}>
                  <Text type="secondary">输入</Text>
                  <TextArea
                    value={testCase.input}
                    onChange={(e) => updateTestCase(index, 'input', e.target.value)}
                    placeholder="请输入测试用例的输入数据"
                    rows={4}
                  />
                </Col>
                <Col span={12}>
                  <Text type="secondary">期望输出</Text>
                  <TextArea
                    value={testCase.output}
                    onChange={(e) => updateTestCase(index, 'output', e.target.value)}
                    placeholder="请输入测试用例的期望输出"
                    rows={4}
                  />
                </Col>
              </Row>
              {index < testCases.length - 1 && <Divider />}
            </div>
          ))}
        </Card>

        {/* 提交按钮 */}
        <div className="form-actions">
          <Space size="large">
            <Button size="large" onClick={() => form.resetFields()}>
              重置
            </Button>
            <Button 
              type="primary" 
              size="large" 
              htmlType="submit" 
              loading={loading}
              icon={<SaveOutlined />}
            >
              {problemId ? '更新题目' : '发布题目'}
            </Button>
          </Space>
            </div>
            </Form>
          </div>
        </div>
      </div>
      
      {/* 创建标签模态框 */}
      <Modal
        title="创建新标签"
        open={isTagModalVisible}
        onCancel={() => {
          setIsTagModalVisible(false);
          tagForm.resetFields();
        }}
        footer={null}
        width={400}
      >
        <Form
          form={tagForm}
          layout="vertical"
          onFinish={handleCreateTag}
        >
          <Form.Item
            name="name"
            label="标签名称"
            rules={[{ required: true, message: '请输入标签名称' }]}
          >
            <Input placeholder="请输入标签名称" maxLength={20} />
          </Form.Item>
          
          <Form.Item
            name="color"
            label="标签颜色"
            initialValue="#1890ff"
            rules={[{ required: true, message: '请选择标签颜色' }]}
          >
            <ColorPicker showText />
          </Form.Item>
          
          <Form.Item
            name="oj"
            label="所属OJ"
            initialValue="swust"
            rules={[{ required: true, message: '请输入所属OJ' }]}
          >
            <Input placeholder="请输入所属OJ" maxLength={20} />
          </Form.Item>
          
          <Form.Item>
            <Space>
              <Button
                type="primary"
                htmlType="submit"
                loading={tagLoading}
              >
                创建标签
              </Button>
              <Button
                onClick={() => {
                  setIsTagModalVisible(false);
                  tagForm.resetFields();
                }}
              >
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ProblemManagement;